package com.gooluke.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gooluke.common.domain.Result;
import com.gooluke.common.util.ExceptionUtil;
import com.gooluke.user.dao.SysUserDao;
import com.gooluke.user.domain.dto.UserCreateDTO;
import com.gooluke.user.domain.vo.UserDetailVO;
import com.gooluke.user.entity.SysUser;
import com.gooluke.user.service.UserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author gooluke
 * description
 * datetime 2025-03-28 17:42
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserDao userDao;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetailVO getUserDetail(Long id) {
        SysUser user = userDao.getById(id);
        if (Objects.isNull(user)) {
            ExceptionUtil.throwDefaultException("用户不存在");
        }
        return UserDetailVO.builder()
                .userId(user.getUserId())
                .userName(user.getUsername())
                .build();
    }

    @Override
    public Result<Object> registerUser(UserCreateDTO dto) {
        SysUser user = userDao.getBaseMapper().selectOne(new QueryWrapper<SysUser>().eq("username", dto.getUserName()));
        if (!Objects.isNull(user)) {
            ExceptionUtil.throwDefaultException("用户名已存在");
        }

        user = SysUser.builder()
                .userId(generateUserId())
                .username(dto.getUserName())
                .password(passwordEncoder.encode(dto.getPassword()))
                .email(dto.getEmail())
                .mobile(dto.getMobile())
                .pwdUpdateTime(LocalDateTime.now())
                .build();

        // 分配默认角色

        //保存用户
        boolean result = userDao.save(user);
        if (!result) {
            ExceptionUtil.throwDefaultException("创建用户失败");
        }
        return Result.success();
    }

    private String generateUserId() {
        String userId = "U_" + RandomStringUtils.random(10, "0123456789");
        int retry = 3;
        do {
            SysUser user = userDao.getBaseMapper().selectOne(new QueryWrapper<SysUser>().eq("user_id", userId));
            if (user == null) {
                return userId;
            }
            retry--;
        } while (retry > 0);
        ExceptionUtil.throwDefaultException("生成用户信息错误");
        return null;
    }

}
